package com.qdxwx.manage.controller.cash;

import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.page.TableDataInfo;
import com.qdxwx.common.utils.DateUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.account.UserAccountDetailService;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.data.service.cash.CashApplyService;
import com.qdxwx.data.service.company.CompanyAccountDetailService;
import com.qdxwx.data.service.company.CompanyAccountService;
import com.qdxwx.data.service.user.UserLetterService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.account.UserAccountDetail;
import com.qdxwx.models.cash.CashApply;
import com.qdxwx.models.company.CompanyAccount;
import com.qdxwx.models.company.CompanyAccountDetail;
import com.qdxwx.models.enums.AccountHistoryType;
import com.qdxwx.models.enums.AccountStatus;
import com.qdxwx.models.enums.CashApplyStatus;
import com.qdxwx.models.enums.LetterTemplate;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.user.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 机构Or用户提现管理Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/cashapply")
public class CashApplyController extends BaseController {

    @Autowired
    private CashApplyService cashApplyService;
    @Autowired
    private CompanyAccountService companyAccountService;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private CompanyAccountDetailService companyAccountDetailService;
    @Autowired
    private UserAccountDetailService userAccountDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserLetterService userLetterService;


    @GetMapping("/list.html")
    @Permissions("cashapply:list")
    public String list() {
        return "cash/cashapply-list";
    }


    @PostMapping("/list.json")
    @ResponseBody
    @Permissions("cashapply:list")
    public TableDataInfo list(HttpServletRequest request) {
        CashApply cashApply = new CashApply();
        cashApply.setInfoId(TKConvert.toInteger(request.getParameter("infoId")));
        cashApply.setStatus(TKConvert.toInteger(request.getParameter("status"), null));
        cashApply.setType(request.getParameter("type"));
        cashApply.setInfoName(request.getParameter("infoName"));
        List<CashApply> list = cashApplyService.getList(cashApply, PageRequest.form(request));
        long count = cashApplyService.count(cashApply);
        return new TableDataInfo(list, count);
    }

    @GetMapping("/view.html")
    public String cashApplyCompany(HttpServletRequest request, ModelMap mmap) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error404;
        CashApply cashApply = cashApplyService.get(id);
        if (cashApply == null) return error404;

        if (cashApply.getType().equalsIgnoreCase("COMPANY")) {
            CompanyAccount companyAccount = companyAccountService.get(cashApply.getInfoId());
            mmap.put("account", companyAccount);
            mmap.put("amounts", companyAccount.getAmount() / 100 + " 元");
        } else {
            UserAccount userAccount = userAccountService.getByUserId(cashApply.getInfoId());
            mmap.put("account", userAccount);
            mmap.put("amounts", userAccount.getBackAmount() / 100 + " + " + userAccount.getVmAmount() / 100 + " 元");
            //userAccount.backAmount/100+' + '+ userAccount.vmAmount/100 + ' 元'
        }
        mmap.put("cashApply", cashApply);
        return "cash/cashapply-view";
    }

    //审核机构提现
    @PostMapping("/apply.json")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult applyCompany(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error("登录超时");
        int cashApplyId = TKConvert.toInteger(request.getParameter("cashApplyId"));
        if (cashApplyId < 1) return error("找不到该提现申请ID");
        int status = TKConvert.toInteger(request.getParameter("status"));
        if (status == 0) return error("参数异常");
        String description = request.getParameter("description");
        CashApply cashApply = cashApplyService.get(cashApplyId);
        if (cashApply == null) return error("找不到该提现申请记录");
        switch (status) {
            case -1:
                //提现申请驳回操作
                cashApply.setCensorName(manager.getManagerName());
                cashApply.setCensorTime(LocalDateTime.now());
                cashApply.setDescription(description);
                cashApply.setStatus(CashApplyStatus.REJECTED.getValue());
                break;
            case 1:
                //提现申请通过操作
                cashApply.setCensorName(manager.getManagerName());
                cashApply.setCensorTime(LocalDateTime.now());
                cashApply.setDescription(description);
                cashApply.setStatus(CashApplyStatus.UNPAID.getValue());
                break;
            case 2:
                //提现申请已支付操作
                cashApply.setPayName(manager.getManagerName());
                cashApply.setPayTime(LocalDateTime.now());
                cashApply.setDescription(description);
                cashApply.setStatus(CashApplyStatus.PAYMENT.getValue());
                break;
            default:
                return error("审核失败");
        }
        int count = cashApplyService.update(cashApply);
        if (count > 0) {
            if (cashApply.getType().equalsIgnoreCase("COMPANY")) {
                applyCompany(cashApply);
            } else {
                applyTeacher(cashApply);
            }
        }
        return toAjax(count);
    }

    public void applyCompany(CashApply cashApply) {
        CompanyAccount companyAccount = companyAccountService.get(cashApply.getInfoId());
        if (companyAccount.getIsDisabled() > 1) {
            throw new RuntimeException("用户被冻结，禁止操作");
        }
        if (cashApply.getStatus() == CashApplyStatus.REJECTED.getValue()) {
            /*创建交易记录*/
            CompanyAccountDetail accountDetail = new CompanyAccountDetail();
            accountDetail.setCompanyId(cashApply.getInfoId());
            accountDetail.setOrderId(0);
            accountDetail.setBefore(companyAccount.getAmount());
            accountDetail.setIncome(cashApply.getAmount());
            accountDetail.setDeduct(0);
            accountDetail.setResult(companyAccount.getAmount() + cashApply.getAmount());
            accountDetail.setFrom("返还提现金额");
            accountDetail.setRemark("返还提现金额" + (cashApply.getAmount() / 100) + "元");
            /*机构账户资金回滚*/
            companyAccount.setAmount(companyAccount.getAmount() + cashApply.getAmount());
            companyAccount.setFrozenAmount(companyAccount.getFrozenAmount() - cashApply.getAmount());
            companyAccount.setVersion(companyAccount.getVersion() + 1);
            /*更新账户信息*/
            if (companyAccountService.update(companyAccount) > 0) {
                /*交易记录保存*/
                accountDetail.setVersion(companyAccount.getVersion());
                companyAccountDetailService.insert(accountDetail);
            }
        } else if (cashApply.getStatus() == CashApplyStatus.PAYMENT.getValue()) {
            //提现申请已支付操作
            //扣除冻结金额
            companyAccount.setFrozenAmount(companyAccount.getFrozenAmount() - cashApply.getAmount());
            companyAccountService.update(companyAccount);
        }
    }

    //审核教师提现
    public void applyTeacher(CashApply cashApply) {
        User user = userService.get(cashApply.getInfoId());
        if (user.getIsAvailable() > 1) {
            throw new RuntimeException("用户被冻结，禁止操作");
        }
        UserAccount userAccount = userAccountService.getByUserId(cashApply.getInfoId());
        if (userAccount.getAccountStatus().equals(AccountStatus.FROZEN.toString())) {
            throw new RuntimeException("账户被禁用，禁止操作");
        }
        if (cashApply.getStatus() == CashApplyStatus.REJECTED.getValue()) {
            //提现申请驳回操作
            /*创建交易记录*/
            UserAccountDetail userAccountDetail = new UserAccountDetail();
            userAccountDetail.setUserId(user.getUserId());
            userAccountDetail.setUserName(user.getUserName());
            userAccountDetail.setEmail(user.getEmail());
            userAccountDetail.setMobile(user.getMobile());
            userAccountDetail.setOrderId(0);
            userAccountDetail.setOtherId(0);
            userAccountDetail.setBalance(userAccount.getBalance());
            userAccountDetail.setVmAmount(userAccount.getVmAmount());
            userAccountDetail.setBackAmount(userAccount.getBackAmount());
            userAccountDetail.setOrderAmount(cashApply.getAmount());
            userAccountDetail.setDescription("返还提现金额");
            userAccountDetail.setActHistoryType(AccountHistoryType.REFUND.toString());
            userAccountDetail.setBizType(AccountHistoryType.BACKMONEY.toString());
            /*账户资金回滚*/
            userAccount.setBackAmount(userAccount.getBackAmount() + cashApply.getAmount());
            userAccount.setBalance(userAccount.getBalance() + cashApply.getAmount());
            userAccount.setFrozenAmount(userAccount.getFrozenAmount() - cashApply.getAmount());
            userAccount.setVersion(userAccount.getVersion() + 1);
            /*更新账户信息*/
            if (userAccountService.update(userAccount) > 0) {
                /*交易记录保存*/
                userAccountDetail.setVersion(userAccount.getVersion());
                userAccountDetailService.insert(userAccountDetail);
            }
        } else if (cashApply.getStatus() == CashApplyStatus.PAYMENT.getValue()) {
            //提现申请已支付操作
            //扣除冻结金额
            userAccount.setFrozenAmount(userAccount.getFrozenAmount() - cashApply.getAmount());
            userAccountService.update(userAccount);
            /*发送消息*/
            userLetterService.send(userAccount.getUserId(), LetterTemplate.CASH_DRAW, DateUtils.toString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
